'use strict';
const crypto = require('crypto');

function aesEncrypt(data, key) {
	const cipher = crypto.createCipher('aes128', key);
	var crypted = cipher.update(data, 'utf8', 'hex');
	crypted += cipher.final('hex');
	return crypted;
}

function aesDecrypt(encrypted, key) {
	const decipher = crypto.createDecipher('aes128', key);
	var decrypted = decipher.update(encrypted, 'hex', 'utf8');
	decrypted += decipher.final('utf8');
	return decrypted;
}
const db = uniCloud.database();
exports.main = async (event, context) => {
	const secKey = ''; // 自定义密钥
	const appid = ''; // 小程序appid
	const appsec = ''; // 小程序appsecret
	const apiUrl = 'https://api.weixin.qq.com/sns/jscode2session';
	const reqType = event.reqType;
	// 用户登录
	if (reqType == 1) {
		try {
			const res = await uniCloud.httpclient.request(apiUrl, {
				method: 'POST',
				data: {
					grant_type: 'authorization_code',
					js_code: event.code,
					secret: appsec,
					appid
				},
				dataType: 'json'
			});
			if (res && res.data && res.data.openid) {
				const encStr = aesEncrypt(res.data.openid, secKey);
				const collection = db.collection('company_employee');
				const totalRes = await collection.where({
					openid: res.data.openid,
				}).count();
				if (totalRes.total === 0) {
					const userInfo = event.userInfo || {};
					delete userInfo.language;
					await collection.add({
						openid: res.data.openid,
						company: '',
						department: '',
						jobnumber: '',
						name: '',
						userType: 'wx',
						...userInfo,
						createTime: Date.now()
					});
				}
				return encStr;
			}
			return null;
		} catch (e) {
			return null;
		}
	}
	// 获取员工信息
	if (reqType == 2) {
		try {
			const decStr = aesDecrypt(event.token, secKey);
			const collection = db.collection('company_employee');
			const res = await collection.field({
				'company': true,
				'department': true,
				'jobnumber': true,
				'name': true
			}).where({
				openid: decStr,
			}).get();
			return res.data && res.data[0] ? res.data[0] : null;
		} catch (e) {
			return null;
		}
	}
	// 绑定员工信息
	if (reqType == 3) {
		try {
			const decStr = aesDecrypt(event.token, secKey);
			const collection = db.collection('company_employee');
			const totalRes = await collection.where({
				openid: decStr,
			}).count();
			if (totalRes.total === 0) {
				return {status: 0, msg: '员工信息不存在'};
			} else {
				const companyNum = await db.collection('company_accout').where({
					company_no: event.company,
				}).count();
				if (companyNum.total === 0) {
					return {status: 0, msg: '企业号不存在'};
				}
				const employee = {
					'company': event.company,
					'department': event.department || '',
					'jobnumber': event.jobnumber,
					'name': event.name
				};
				await collection.where({
				  openid: decStr,
				}).update(employee);
				return {
					status: 1,
					employee
				}
			}
		} catch (e) {
			return null;
		}
	}
	// 解除绑定企业信息
	if (reqType == 4) {
		try {
			const decStr = aesDecrypt(event.token, secKey);
			const collection = db.collection('company_employee');
			const employee = {
				'company': '',
				'department': '',
				'jobnumber': '',
				'name': ''
			};
			await collection.where({
			  openid: decStr,
			}).update(employee);
			return {
				status: 1,
				employee
			}
		} catch (e) {
			return null;
		}
	}
	return null;
};
